import axios from 'axios'
import { showLoading, hideLoading } from '@/assets/components/Loading'

const instance = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 5000, //超时时间
})

//配置请求拦截器,在请求之前的数据处理,比如在请求头添加token,所有的请求都会经过拦截器
instance.interceptors.request.use(
  //config:该参数表示当前请求的配置对象
  (config) => {
    showLoading()
    //在请求头统一添加token
    //或者请求之前显示lodding图标(这里只演示这个)
    return config
  },
  (err) => {
    return Promise.reject(err)
  },
)

//配置响应拦截器
instance.interceptors.response.use(
  (response) => {
    hideLoading()
    const httpStatus = response.status
    if (httpStatus !== 200) {
      ElMessage({ message: '服务器错误', type: 'error' })
    }
    let apiStatus = response.data.code
    const requestURL = response.request.responseURL
    if (requestURL.includes('/bing')) {
      return response.data.images
    }
    switch (apiStatus) {
      case '200':
        alertMessage(response.request.responseURL)
        return response.data.data
      default:
        ElMessage.error({ message: '接口错误', type: 'error' })
        break
    }
    return response
  },
  (err) => {
    hideLoading()
    return Promise.reject(err)
  },
)
const alertMessage = (url) => {
  const regex = /insert|update|delete/i
  if (regex.test(url)) {
    ElMessage({ message: '成功', type: 'success' })
  }
}

//封装请求的api
const api = (method = 'GET', url, data = {}) => {
  return instance({
    method,
    url,
    params: method === 'GET' ? data : {},
    data:
      method === 'POST' || method === 'PUT' || method === 'delete' ? data : {},
  })
}

export const get = (url, data) => api('GET', url, data)
export const post = (url, data) => api('POST', url, data)
export const put = (url, data) => api('PUT', url, data)
export const deleteApi = (url, data) => api('delete', url, data)
